package com.wuyou.securitydemo.handler;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpUtil;
import com.wuyou.sso.common.contant.AuthConstants;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 表单登陆失败
 *
 * @Date 2025/4/1 10:10
 * @Author 无忧
 */
@Slf4j
public class CustomizedFormLoginFailureHandler implements AuthenticationFailureHandler {

    @SneakyThrows
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.error("表单登录失败->{}", exception.getLocalizedMessage());
        String url =
                HttpUtil.encodeParams(
                        String.format(AuthConstants.FORM_LOGIN_URI + "?error=%s", exception.getMessage()),
                        CharsetUtil.CHARSET_UTF_8);
        ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getResponse()
                .sendRedirect(url);
    }
}
